package lumis.service.mailmarketing;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

import org.hibernate.Session;

import lumis.content.ContentException;
import lumis.content.ContentStringResource;
import lumis.doui.processaction.ProcessActionHandler;
import lumis.portal.PortalException;
import lumis.portal.dao.hibernate.ITransactionHibernate;
import lumis.util.IResource;

/**
 * Adds the selected categories to the bulletin
 *
 * @version $Revision: 7943 $ $Date: 2007-08-10 15:11:07 -0300 (Fri, 10 Aug 2007) $
 * @since 4.0.6
 */
public class MailMarketingBulletinAddDataProcessActionHandler extends ProcessActionHandler
{

	public void processAction() throws PortalException 
	{
		String bulletinId = (String)this.douiContext.getRequest().getAttribute("itemId");
		IResource resource = new ContentStringResource();
		resource.addResourcePath("lumis/service/mailmarketing/strings/strings");
		
		ITransactionHibernate transactionHib = (ITransactionHibernate) transaction;
		Session session = transactionHib.getSession();
		
		Bulletin bulletin = (Bulletin)session.get(Bulletin.class, bulletinId);
		
		String[] categoryIds = (String[])getParameter("categoryId");
		
		if(categoryIds == null || categoryIds.length == 0)
			throw new ContentException("STR_MUST_SELECT_ONE_CATEGORY", resource);
		
		Collection<Category> categories = bulletin.getCategories();

		Collection<String> categoryIdsToSet = new ArrayList<String>(Arrays.asList(categoryIds));
		for (Iterator<Category> itCategories = categories.iterator(); itCategories.hasNext(); )
		{
			Category category = itCategories.next();
			
			// if the category is not in the ids collection to be set, remove it
			if (!categoryIdsToSet.remove(category.getId()))
				itCategories.remove();
		}
		
		// add categories that were not already set
		for(String categoryId : categoryIdsToSet)
		{
			Category categoryConfig = (Category)session.load(Category.class, categoryId);
			categories.add(categoryConfig);
		}

		addDefaultResponse();
	}
}
